package com.mobilebsc.httpclient.callback;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.mobilebsc.datatype.KPI;

public class KPIHttpResponseHandler extends JsonHttpResponseHandler {

	private static final String TAG = "KPIHttpResponseHandler";
	private IAsyncTaskCompleteListener<List<KPI>> callback;
	protected List<KPI> kpiList;

	public KPIHttpResponseHandler(IAsyncTaskCompleteListener<List<KPI>> callback) {
		super();
		this.callback = callback;
		kpiList = null;
	}

	@Override
	public void onStart() {
		Log.i(TAG, "onStart = loading data");
	}

	@Override
	public void onSuccess(JSONArray kpis) {

		Log.i(TAG, "onSuccess = JSON length " + kpis.length()
				+ ", JSON string " + kpis.toString());

		kpiList = new ArrayList<KPI>();
		JSONObject kpiJSON = new JSONObject();

		if (kpis.length() == 0) {
			kpiList.add(new KPI());
		} else {
			for (int i = 0; i < kpis.length(); i++) {
				try {
					kpiJSON = kpis.getJSONObject(i);
					KPI kpi = new KPI(kpiJSON);
					kpiList.add(kpi);
				} catch (JSONException e) {
					Log.e(TAG, "onSuccess = " + e.toString());
				}
			}
		}
	}

	@Override
	public void onSuccess(JSONObject singleKPI) {
		kpiList = new ArrayList<KPI>();

		if (singleKPI == null) {
			kpiList.add(new KPI());
		} else {
			try {
				KPI kpi = new KPI(singleKPI);
				kpiList.add(kpi);
			} catch (JSONException e) {
				Log.e(TAG, "onSuccess = " + e.toString());
			}
		}
	}

	@Override
	public void onFinish() {
		Log.i(TAG, "onFinish = finished");
		callback.onTaskComplete(kpiList);
	}

	@Override
	public void onFailure(Throwable e, String response) {
		Log.e(TAG, "onFailure = " + e.toString() + "\n\n" + response);
	}
}